package garage

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/garage"
	garageReq "github.com/flipped-aurora/gin-vue-admin/server/model/garage/request"
)

type GarageService struct {
}

// CreateGarage 创建garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garageService *GarageService) CreateGarage(garage *garage.Garage) (err error) {
	err = global.GVA_DB.Create(garage).Error
	return err
}

// DeleteGarage 删除garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garageService *GarageService) DeleteGarage(garage garage.Garage) (err error) {
	err = global.GVA_DB.Delete(&garage).Error
	return err
}

// DeleteGarageByIds 批量删除garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garageService *GarageService) DeleteGarageByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]garage.Garage{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateGarage 更新garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garageService *GarageService) UpdateGarage(garage garage.Garage) (err error) {
	err = global.GVA_DB.Save(&garage).Error
	return err
}

// GetGarage 根据id获取garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garageService *GarageService) GetGarage(id uint) (garage garage.Garage, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&garage).Error
	return
}

// GetGarageInfoList 分页获取garage表记录
// Author [piexlmax](https://github.com/piexlmax)
func (garageService *GarageService) GetGarageInfoList(info garageReq.GarageSearch) (list []garage.Garage, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&garage.Garage{})
	var garages []garage.Garage
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&garages).Error
	return garages, total, err
}

func (garageService *GarageService) GetGarageInfoListNoPage() (list []garage.Garage, err error) {
	db := global.GVA_DB.Model(&garage.Garage{})
	var garages []garage.Garage
	err = db.Find(&garages).Error
	return garages, err
}
